<?php

namespace App\Http\Model;
use Cache;

class GoodsSku extends Base
{
    public $timestamps = false;
    /**
     * 定义数据库表名
     *
     * @var string
     */
    protected $table = 'goods_sku';

    /**
     * 定义主键名
     *
     * @var string
     */
    protected $primaryKey = 'sku_id';


    public static function boot()
    {
        //保存之后修改缓存
        GoodsSku::saved(function($post){
            $cacheKey = 'goods_sku_'.$post->sku_id;
            $cacheData = Cache::get($cacheKey);
            if(!$cacheData){
                Cache::add($cacheKey,$post,60*24*7);
            }else{
                Cache::put($cacheKey,$post,60*24*7);
            }
        });

        //删除之后清除缓存数据
        GoodsSku::deleted(function($post){
            $cacheKey = 'goods_sku_'.$post->sku_id;
            $cacheData = Cache::get($cacheKey);
            if($cacheData){
                Cache::forget($cacheKey);
            }
        });
    }

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'sku_id',
        'create_time',
        'update_time',
        'delete_time',
    ];

    public function setGoods($goods)
    {
        $this->goods_id = $goods->goods_id;

        return $this;
    }

    public function goods()
    {
        return $this->belongsTo(Goods::class, 'goods_id', 'goods_id');
    }

    public function propertyValue()
    {
        return $this->hasMany(GoodsProperty::class, 'goods_id', 'goods_id');
    }

    public function comments()
    {
        return $this->hasMany(GoodsComment::class, 'sku_id', 'sku_id');
    }


    public function img()
    {
        return $this->hasOne(Img::class, 'id', 'img_id');
    }


    public function imgs()
    {
        return $this->belongsToMany(Img::class, 'goods_img', 'sku_id', 'img_id');
    }

    public function activeGoods()
    {
        return $this->hasOne(ActiveGoods::class, 'sku_id', 'sku_id');
    }


    public function getPrice()
    {
        if ($this->activeGoods) {
            return $this->price * $this->activeGoods->active->deposit_rate;
        }
        return (float)$this->price;
    }

    public function checkStock($num)
    {
        return $this->quantity_sale + $num > $this->quantity ? false :true;
    }
}
